﻿using System;
using biz.ritter.javapi.lang;
using biz.ritter.javapi.io;
using Nofs.Net.Cache.Impl;
using biz.ritter.javapi.xml;
using biz.ritter.javapi.util;

namespace Nofs.Net.nofs.metadata.XMLDriver
{
   
public sealed class XMLFileSystem {
	
	private static String ReadFile(String fileName) //throws IOException 
    {
		StringBuffer buff = new StringBuffer((int)new File(fileName).length());
		InputStream input = new FileInputStream(fileName);
		byte[] buffer = new byte[1024];
		int len;
		while((len = input.read(buffer)) != (-1)) {
			for(int i = 0; i < len; i++) {
				buff.append((char)buffer[i]);
			}
		}
        input.close();
		return buff.toString();
	}
	
	public void ReadFromXML(String fileName) //throws Exception 
    {
		Document document = DocumentHelper.parseText(ReadFile(fileName));
		Branch fsNode = XMLHelper.TryToFindChildByName(document, "FileSystem");
		if(fsNode == null) {
			throw new System.Exception("invalid fs document");
		}
		_rootFolderClassName = XMLHelper.TryReadChildContents(fsNode, "RootFolderClassName", null);
		Branch domainObjectsNode = XMLHelper.TryToFindChildByName(fsNode, "DomainObjects");
		if(domainObjectsNode == null) {
			throw new System.Exception("must defined domain objects");
		}
		_domainObjects = new LinkedList<XMLDomainObject>();
		foreach(Branch domainNode in XMLHelper.GetChildren(domainObjectsNode)) {
			XMLDomainObject domainObj = new XMLDomainObject();
			domainObj.ReadFromXML(domainNode);
			_domainObjects.add(domainObj);
		}
	}
	
	private String _rootFolderClassName;
	public String RootFolderClassName() { return _rootFolderClassName; }
	
	private LinkedList<XMLDomainObject> _domainObjects;
	public LinkedList<XMLDomainObject> DomainObjects()
    {
        LinkedList<XMLDomainObject> list = new LinkedList<XMLDomainObject>();
        list.addAll(Collections.unmodifiableList(_domainObjects));
        return list; 
    }
	
	public XMLDomainObject GetDomainObjectByName(String name) //throws Exception 
    {
		foreach(XMLDomainObject candidate in _domainObjects) {
			if(candidate.ClassName().CompareTo(name) == 0) {
				return candidate;
			}
		}
		throw new System.Exception("could not find domain object with name = " + name);
	}
	
	public XMLDomainObject TryGetDomainObjectByName(String name) //throws Exception 
    {
		foreach(XMLDomainObject candidate in _domainObjects) {
			if(candidate.ClassName().compareTo(name) == 0) {
				return candidate;
			}
		}
		return null;
	}
	
}
}
